// 网络连接检测工具

/**
 * 检测网络连接状态
 */
export const checkNetworkConnection = async (): Promise<boolean> => {
  try {
    // 使用AbortController实现超时
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), 5000)
    
    // 尝试访问一个简单的API端点
    const response = await fetch('/api/health', {
      method: 'GET',
      cache: 'no-cache',
      signal: controller.signal
    })
    
    clearTimeout(timeoutId)
    return response.ok
  } catch (error) {
    return false
  }
}

/**
 * 检测是否可能是浏览器扩展冲突
 */
export const detectExtensionConflict = (error: any): boolean => {
  const conflictIndicators = [
    'message port closed',
    'Extension context invalidated',
    'Could not establish connection',
    'The message port closed before a response was received'
  ]
  
  const errorMessage = error?.message || error?.toString() || ''
  return conflictIndicators.some(indicator => 
    errorMessage.toLowerCase().includes(indicator.toLowerCase())
  )
}

/**
 * 获取网络诊断信息
 */
export const getNetworkDiagnostics = async () => {
  const diagnostics = {
    online: navigator.onLine,
    connection: (navigator as any).connection,
    userAgent: navigator.userAgent,
    timestamp: new Date().toISOString()
  }
  
  // 检测可能冲突的浏览器扩展
  const commonConflictingExtensions = [
    'adblock',
    'ublock',
    'ghostery',
    'privacy badger',
    'disconnect'
  ]
  
  return {
    ...diagnostics,
    potentialConflicts: commonConflictingExtensions,
    recommendations: [
      '尝试在无痕模式下访问（禁用扩展）',
      '暂时禁用广告拦截器和隐私保护扩展',
      '检查网络连接是否稳定',
      '清除浏览器缓存和Cookie',
      '尝试使用其他浏览器'
    ]
  }
}

/**
 * 显示网络问题解决建议
 */
export const showNetworkTroubleshooting = () => {
  const suggestions = [
    '🔧 **网络连接问题排查建议：**',
    '',
    '1. **检查网络连接**',
    '   - 确认网络连接正常',
    '   - 尝试访问其他网站',
    '',
    '2. **浏览器扩展冲突**',
    '   - 在无痕模式下重试',
    '   - 暂时禁用广告拦截器',
    '   - 禁用隐私保护扩展',
    '',
    '3. **浏览器问题**',
    '   - 清除浏览器缓存',
    '   - 重启浏览器',
    '   - 尝试其他浏览器',
    '',
    '4. **如果问题持续存在**',
    '   - 联系系统管理员',
    '   - 检查防火墙设置'
  ]
  
  return suggestions.join('\n')
}